﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Com.Alipay;
namespace StoreWeb.ajax
{
    public partial class order : System.Web.UI.Page
    {
        public static string PostUrl = ConfigurationManager.AppSettings["WebReference.Service.PostUrl"];
        Maticsoft.BLL.Orders bll = new Maticsoft.BLL.Orders();
        Maticsoft.BLL.Ordersize ordersizebll = new Maticsoft.BLL.Ordersize();
        Maticsoft.BLL.Ordertetisize ordertetisizebll = new Maticsoft.BLL.Ordertetisize();
        Maticsoft.BLL.Parts Partsbll = new Maticsoft.BLL.Parts();
        Maticsoft.BLL.style stylebll = new Maticsoft.BLL.style();
        Maticsoft.BLL.membersize mbsizebll = new Maticsoft.BLL.membersize();
        Maticsoft.BLL.InventoryClass classbll = new Maticsoft.BLL.InventoryClass();
        Maticsoft.BLL.Inventory itbll = new Maticsoft.BLL.Inventory();
        BLL.member mbbll = new BLL.member();
        BLL.memberGrade gdbll = new BLL.memberGrade();
        Maticsoft.BLL.membersize sizebll = new Maticsoft.BLL.membersize();
        BLL.DealersManage dmbll = new BLL.DealersManage();
        BLL.DealersGrade dgbll = new BLL.DealersGrade();
        BLL.StoreCheckAccount scabll = new BLL.StoreCheckAccount();
        Maticsoft222.BLL.sqlexec sqlexec = new Maticsoft222.BLL.sqlexec();
        Maticsoft.BLL.productsconnection pcbll = new Maticsoft.BLL.productsconnection();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                switch (Request["action"])
                {
                    case "getParts":
                        getParts(Request["id"]);
                        break;
                    case "getStyle":
                        getStyle(Request["id"]);
                        break;
                    case "getPartsbyclnvCName":
                        getPartsbyclnvCName(Request["id"]);
                        break;
                    case "getphonecode":
                        getphonecode();
                        break;
                    case "delete":
                        delete(Request["id"]);
                        break;
                    case "orderbuy":
                        orderbuy(Request["id"]);
                        break;
                    case "orderdaoliao":
                        orderdaoliao(Request["id"]);
                        break;
                    case "orderruku":
                        orderruku(Request["id"]);
                        break;
                    case "storetoerporder":
                        storetoerporder(Request["ordercodes"]);
                        break;
                    case "getmianliaocInvStd":
                        getmianliaocInvStd(Request["cinvccode"]);
                        break;
                    case "getxinghaobycinvcname":
                        getxinghaobycinvcname(Request["cinvcname"]);
                        break;
                    case "ordershend":
                        ordershend();
                        break;
                    case "getInventory":
                        getInventory(Request["cinvcname"]);
                        break;
                    case "updateorder":
                        updateorder(Request["id"]);
                        break;
                    case "getproductconnection":
                        getproductconnection(Request["id"]);
                        break;
                    case "getordersize":
                        getordersize(Request["id"]);
                        break;
                    case "checkorderstatus":
                        checkorderstatus(Request["id"]);
                        break;

                    case "getInventoryClassJson":
                        getInventoryClassJson(Request["id"]);
                        break;
                }
            }
        }
        private void getInventoryClassJson(string InventoryClassID)
        {

            Response.Write(JsonConvert.SerializeObject(sqlexec.query("select a.cinvcname as name,b.cInvStd as cinvstd,a.price,b.cinvcode as code from dbo.InventoryClass a left join Inventory b on a.cInvCCode=b.cInvCCode where a.cInvCCode like '" + InventoryClassID + "%' and a.iInvCGrade<>1 and binvcend=1 order by a.cInvCCode asc").Tables[0]));

        }
        private void checkorderstatus(string orderid)
        {
            Maticsoft.Model.Orders md = bll.GetModel(Convert.ToInt32(orderid));
            Response.Write(md.orderstatus == 8 ? "1" : "0");
        }
        private void getproductconnection(string cinvCCode)
        {
            List<Maticsoft.Model.productsconnection> lists = pcbll.GetModelList("cinvCCode='" + cinvCCode + "'");
            Response.Write(JsonConvert.SerializeObject(new { istz = lists != null && lists.Count > 0 ? true : false, list = lists }));
        }
        private void getordersize(string orderid)
        {
            Maticsoft.Model.Orders md = bll.GetModel(Convert.ToInt32(orderid));
            Response.Write(JsonConvert.SerializeObject(ordersizebll.GetModelList("ordercode='" + md.code + "' and tzgroup='" + Request["tzgroup"] + "'")));
        }
        //修改订单尺寸
        private void updateorder(string id)
        {
            Maticsoft.Model.Orders md = bll.GetModel(Convert.ToInt32(id));
            if (md != null)
            {
                List<Maticsoft.Model.Ordersize> ordersizemodel = JsonConvert.DeserializeObject<List<Maticsoft.Model.Ordersize>>(Request["hidsize"]);
                List<Maticsoft.Model.Ordertetisize> ordertetisizemodel = JsonConvert.DeserializeObject<List<Maticsoft.Model.Ordertetisize>>(Request["hidtetisize"]);
                //List<Maticsoft.Model.membersize> mlist = mbsizebll.GetModelList("sizecode='" + md.size + "' and membercode='" + md.membermobile + "'");
                List<Maticsoft.Model.Ordersize> ordersizes = ordersizebll.GetModelList("ordercode='" + md.code + "'");
                List<Maticsoft.Model.Ordertetisize> ordertetisizes = ordertetisizebll.GetModelList("ordercode='" + md.code + "'");
                md.imgs = Request["urls"];
                md.note = Request["content"];
                md.size = Request["size"];
                bll.Update(md);
                //修改订单尺寸
                if (ordersizemodel != null && ordersizemodel.Count > 0)
                {
                    //sqlexec.ExecuteSql("delete Ordersize where ordercode='" + md.code + "'");
                    foreach (var item in ordersizemodel)
                    {
                        if (ordersizes.Any(c => c.sizeid == item.sizeid))
                        {
                            item.id = ordersizes.First(c => c.sizeid == item.sizeid).id;
                            ordersizebll.Update(item);
                        }
                        else
                        {
                            ordersizebll.Add(item);
                        }
                        //保存客户尺寸
                        //Maticsoft.Model.membersize membersize = new Maticsoft.Model.membersize();
                        //membersize.sizecode = item.sizecode;
                        //membersize.name = item.sizename;
                        //membersize.sizeid = Convert.ToInt32(item.sizeid);
                        //membersize.value = item.sizevalue;
                        //if (mlist.Any(c => c.sizeid == Convert.ToInt32(item.sizeid)))
                        //{
                        //    membersize.id = mlist.First(c => c.sizeid == Convert.ToInt32(item.sizeid)).id;
                        //    mbsizebll.Update(membersize);
                        //}
                        //else
                        //{
                        //    mbsizebll.Add(membersize);
                        //}
                    }
                }
                //修改特体尺寸
                if (ordertetisizemodel != null && ordertetisizemodel.Count > 0)
                    foreach (var item in ordertetisizemodel)
                    {
                        if (ordertetisizes.Any(c => c.groupname == item.groupname && c.tzgroup == item.tzgroup))
                        {
                            item.id = ordertetisizes.First(c => c.groupname == item.groupname && c.tzgroup == item.tzgroup).id;
                            ordertetisizebll.Update(item);
                        }
                        else
                        {
                            ordertetisizebll.Add(item);
                        }
                    }
                Response.Write("1");
            }
            else
                Response.Write("0");
        }
        //面料信息
        private void getInventory(string cinvcname)
        {
            Maticsoft.Model.InventoryClass icbll = classbll.GetModelList("cInvCCode like '01%' and iInvCGrade<>1 and cinvcname='" + cinvcname + "'").First();
            if (icbll != null)
                Response.Write(JsonConvert.SerializeObject(classbll.GetModelList("cInvCCode like '" + icbll.cInvCCode + "%' and iInvCGrade<>1 order by cInvCCode asc")));
            else
                Response.Write("[]");
        }
        private void orderdaoliao(string orderid)
        {
            Maticsoft.Model.Orders order = bll.GetModel(Convert.ToInt32(orderid));

            order.orderstatus = 4;//已到料
            //修改订单状态
            Response.Write(bll.Update(order) ? "1" : "0");
        }
        private void orderruku(string orderid)
        {
            Maticsoft.Model.Orders order = bll.GetModel(Convert.ToInt32(orderid));

            order.orderstatus = 7;
            //修改订单状态
            Response.Write(bll.Update(order) ? "1" : "0");
        }
        /// <summary>
        /// 订单发货
        /// </summary>
        private void ordershend()
        {
            //修改快递
            if (!string.IsNullOrEmpty(Request["ordercodes"]))
            {
                string account = ConfigurationManager.AppSettings["WebReference.Service.account"];
                string password = ConfigurationManager.AppSettings["WebReference.Service.password"];
                string content = "您好，您的验证码是123";
                //string content = "您好，你订购的服装已经通过" + Request["name"] + "(" + Request["ddlistkuaidi"] + ")发货,请注意查收,感谢您的惠顾！";

                string postStrTpl = "account={0}&pswd={1}&mobile={2}&msg={3}&needstatus=true&extno=";

                UTF8Encoding encoding = new UTF8Encoding();

                foreach (var item in Request["ordercodes"].Split(','))
                {
                    Maticsoft.Model.Orders md = bll.GetModelList("code = '" + item + "'")[0];
                    string mobile = md.membermobile;
                    byte[] postData = encoding.GetBytes(string.Format(postStrTpl, account, password, mobile, content));
                    HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(PostUrl);
                    myRequest.Method = "POST";
                    myRequest.ContentType = "application/x-www-form-urlencoded";
                    myRequest.ContentLength = postData.Length;

                    Stream newStream = myRequest.GetRequestStream();
                    // Send the data.
                    newStream.Write(postData, 0, postData.Length);
                    newStream.Flush();
                    newStream.Close();
                    md.crname = Request["ddlistkuaidi"];
                    md.crvalue = Request["name"];
                    bll.Update(md);
                }
            }
            Response.Write(sqlexec.ExecuteSql("exec STORE_TO_ERP_ORDERSEND '" + Request["ordercodes"] + "'") ? "1" : "");
        }
        /// <summary>
        /// 根据产成品分类名称获取尺寸信息
        /// </summary>
        /// <param name="cinvcname"></param>
        private void getxinghaobycinvcname(string cinvcname)
        {
            Response.Write(JsonConvert.SerializeObject(sqlexec.query("select a.cinvstd from Inventory a left join InventoryClass b on a.cinvccode=b.cinvccode where a.cinvccode like '05%' and a.ptype=2 and b.cinvcname='" + cinvcname + "'").Tables[0]));
        }
        /// <summary>
        /// 根据面料分类获取面料信息
        /// </summary>
        /// <param name="cinvccode"></param>
        private void getmianliaocInvStd(string cinvccode)
        {
            Response.Write(JsonConvert.SerializeObject(itbll.GetModelList("cinvccode='" + cinvccode + "'").Select(c => new { code = c.cInvCode, name = c.cInvName, cinvstd = c.cInvStd, price = classbll.GetModelList("cinvccode='" + cinvccode + "'")[0].price }).ToList()));
        }
        private void delete(string id)
        {
            Maticsoft.Model.Orders ordr = bll.GetModel(Convert.ToInt32(id));
            ordr.orderstatus = 0;
            Response.Write(bll.Update(ordr) ? 1 : 0);
        }
        /// <summary>
        /// 根据手机号获取验证码 如果是会员则返回会员信息
        /// </summary>
        private void getphonecode()
        {
            //System.Random a = new Random(System.DateTime.Now.Millisecond);
            //int RandKey = a.Next(100000, 999999);
            //string account = ConfigurationManager.AppSettings["WebReference.Service.account"];
            //string password = ConfigurationManager.AppSettings["WebReference.Service.password"];
            //string mobile = Request["mobile"];
            //string content = "您好，您的验证码是" + RandKey + "";

            //string postStrTpl = "account={0}&pswd={1}&mobile={2}&msg={3}&needstatus=true&extno=";

            //UTF8Encoding encoding = new UTF8Encoding();
            //byte[] postData = encoding.GetBytes(string.Format(postStrTpl, account, password, mobile, content));

            //HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(PostUrl);
            //myRequest.Method = "POST";
            //myRequest.ContentType = "application/x-www-form-urlencoded";
            //myRequest.ContentLength = postData.Length;

            //Stream newStream = myRequest.GetRequestStream();
            //// Send the data.
            //newStream.Write(postData, 0, postData.Length);
            //newStream.Flush();
            //newStream.Close();

            //HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
            //bool issend = false;
            //if (myResponse.StatusCode == HttpStatusCode.OK)
            //{
            //    StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
            //    issend = true;
            //}
            List<Model.member> mblist = mbbll.GetModelList("mobile='" + Request["mobile"] + "'");
            Model.memberGrade grade = null;
            if (mblist.Count > 0 && mblist[0].isvip == "1" && mblist[0].membergrade != null)
                grade = gdbll.GetModel(mblist[0].membergrade.Value);
            List<Maticsoft.Model.membersize> mbszlist = sizebll.GetModelList("membercode='" + Request["mobile"] + "'");
            //Response.Write(JsonConvert.SerializeObject(new { issend = issend, code = RandKey, grade = grade, member = mblist.Count > 0 ? mblist[0] : null }));
            //Response.Write(JsonConvert.SerializeObject(new { grade = grade, sizelist = mbszlist.Select(c => c.sizecode == Request["size"]).ToList(), member = mblist.Count > 0 ? mblist[0] : null }));
            Response.Write(JsonConvert.SerializeObject(new { grade = grade, member = mblist.Count > 0 ? mblist[0] : null }));
        }
        private void getParts(string cInvCCode)
        {
            List<Maticsoft.Model.Parts> list = Partsbll.GetModelList("clnvCCode='" + cInvCCode + "'");
            Response.Write(list.Count > 0 ? JsonConvert.SerializeObject(list.Select(c => new { c.code, c.name }).ToList()) : "[]");
        }
        private void getPartsbyclnvCName(string clnvCName)
        {
            List<Maticsoft.Model.InventoryClass> classlist = classbll.GetModelList("cInvCName='" + clnvCName + "' and binvcend=1");
            List<Maticsoft.Model.Parts> list = Partsbll.GetModelList("clnvCCode='" + (classlist.Count > 0 ? classlist[0].cInvCCode : "") + "'");
            Response.Write(list.Count > 0 ? JsonConvert.SerializeObject(list.Select(c => new { c.code, c.name }).ToList()) : "[]");
        }
        private void getStyle(string partscode)
        {
            List<Maticsoft.Model.style> list = stylebll.GetModelList("partscode='" + partscode + "'");
            Response.Write(list.Count > 0 ? JsonConvert.SerializeObject(list.Select(c => new { c.code, c.partscode, c.partsname, c.cInvCode, c.xiaoguourl, c.dtype, c.bantuurl, c.cInvName, c.price, c.ispricedingdan }).ToList()) : "[]");
        }
        private void orderbuy(string orderid)
        {
            Maticsoft.Model.Orders order = bll.GetModel(Convert.ToInt32(orderid));
            HttpCookie cookie = Request.Cookies["UserLogin"];
            Model.DealersManage dm = dmbll.GetModel(Convert.ToInt32(cookie.Values["dmid"]));
            if (order != null && order.orderpaystatus == 2)
            {
                //获取经销商等级折扣
                Model.DealersGrade md = dgbll.GetModelList("grade='" + dm.dealersgrade + "'").First();
                //计算经销商应付金额
                Decimal mdprice = Convert.ToDecimal(md.discountrate) * Convert.ToDecimal(order.backupprice);
                if (Request["paytype"] == "3")
                {
                    if (dm.moneybalance < mdprice)
                    {
                        Response.Write("2");//余额不足
                    }
                    else
                    {
                        //保存对账单
                        Model.StoreCheckAccount scmd = new Model.StoreCheckAccount();
                        scmd.createtime = DateTime.Now;
                        scmd.createuser = Convert.ToInt32(cookie.Values["ID"]);
                        scmd.changemoney = mdprice;//支出
                        scmd.dealersid = cookie.Values["dmid"];
                        scmd.description = (order.price - mdprice).ToString();//收入
                        scmd.newmoney = dm.moneybalance - mdprice;//余额
                        scmd.oldmoney = dm.moneybalance;
                        scmd.type = "销售订单 <a href=\"javascript:;\" onclick=\"detail(\'订单详细\',\'../order/detail.aspx?id=" + orderid + "\')\">" + order.code + "</a>";
                        scmd.typeid = order.id;
                        scabll.Add(scmd);
                        //修改订单状态
                        order.orderpaystatus = 1;
                        dm.moneybalance -= mdprice;
                        order.dmprice = mdprice;//保存经销商出价
                        Response.Write((bll.Update(order) && dmbll.Update(dm)) ? "1" : "0");
                    }
                }
                //支付宝支付
                else if (Request["paytype"] == "0")
                {
                    ////////////////////////////////////////////请求参数////////////////////////////////////////////

                    //商户订单号，商户网站订单系统中唯一订单号，必填
                    string out_trade_no = order.code;

                    //订单名称，必填
                    string subject = "绯特西服定制";

                    //付款金额，必填
                    string total_fee = mdprice.ToString("f2");
                    //string total_fee = "0.01".ToString();

                    //商品描述，可空
                    string body = "";
                    ////////////////////////////////////////////////////////////////////////////////////////////////

                    //把请求参数打包成数组
                    SortedDictionary<string, string> sParaTemp = new SortedDictionary<string, string>();
                    sParaTemp.Add("service", Com.Alipay.Config.service);
                    sParaTemp.Add("partner", Com.Alipay.Config.partner);
                    sParaTemp.Add("seller_id", Com.Alipay.Config.seller_id);
                    sParaTemp.Add("_input_charset", Com.Alipay.Config.input_charset.ToLower());
                    sParaTemp.Add("payment_type", Com.Alipay.Config.payment_type);
                    sParaTemp.Add("notify_url", Com.Alipay.Config.notify_url);
                    sParaTemp.Add("return_url", Com.Alipay.Config.return_url);
                    sParaTemp.Add("anti_phishing_key", Com.Alipay.Config.anti_phishing_key);
                    sParaTemp.Add("exter_invoke_ip", Com.Alipay.Config.exter_invoke_ip);
                    sParaTemp.Add("out_trade_no", out_trade_no);
                    sParaTemp.Add("subject", subject);
                    sParaTemp.Add("total_fee", total_fee);
                    sParaTemp.Add("body", body);
                    sParaTemp.Add("extra_common_param", cookie.Values["ID"] + "|" + cookie.Values["dmid"]);

                    //建立请求
                    string sHtmlText = Submit.BuildRequest(sParaTemp, "get", "确认");
                    Response.Write(sHtmlText);
                }
            }
        }
        private void storetoerporder(string ordercodes)
        {
            Response.Write(sqlexec.ExecuteSql("exec STORE_TO_ERP_ORDER '" + ordercodes + "'") ? "1" : "");
        }
    }
}